package com.tiger.sendmessage.caspOpeapi;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tiger.db.entity.Users;
import com.tiger.sendmessage.Db;
import com.tiger.sendmessage.type.WechatConfig;
import com.tiger.sendmessage.wechatapi.Wechatapi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

@Service
public class SendMsg {

    //private String contextPath;


    @Value("${APP_HOST}")
    private String APP_HOST;


    private final Db db;
    private final Openapi openapi;
    private final Wechatapi wechatapi;
    private final WechatConfig wechatConfig;

    public SendMsg(Db db, Openapi openapi, Wechatapi wechatapi, WechatConfig wechatConfig) {
        this.db = db;
        this.openapi = openapi;
        this.wechatapi = wechatapi;
        this.wechatConfig = wechatConfig;
    }

    @Async
    public void sendMsg() {
        System.out.println("开始发送消息");
        String[] keys = wechatConfig.getMsgTemplateFields().split(",");


        String contextPath = "/clientApi";

        int pageNo = 1;
        int pageSize = 2000;

        String baseUrl = APP_HOST;
        if(!contextPath.isEmpty()) {
            baseUrl += contextPath;
        }

        baseUrl += "/home/message";

        while (true) {
            List<Users> users = db.users.pagination(new LambdaQueryWrapper<Users>().ne(Users::getOpenid, ""), pageNo, pageSize);
            pageNo ++;

            for(Users user:users) {
                if(!user.getOpenid().isEmpty()) {

                    List<HashMap> rows = openapi.unReadmessage(user.getAccount());
                    if(rows != null && !rows.isEmpty()) {
                        for(HashMap row:rows) {
                            try{

                                HashMap<String, HashMap<String, Object>> msgData = new HashMap<>();
                                String title = (String) row.get("msgTitle");
                                if(title.length() > 20) {
                                    title = title.substring(0, 17) + "...";
                                }
                                String mobileUrl = (String) row.get("mobileUrl");
                                String pcUrl = (String) row.get("pcUrl");

                                String url = baseUrl + ("?mobileUrl=" + URLEncoder.encode(mobileUrl, StandardCharsets.UTF_8)) + "&pcUrl=" + URLEncoder.encode(pcUrl, StandardCharsets.UTF_8);


                                String[] values = {title, (String) row.get("msgSendDate")};
                                for(int i = 0; i < keys.length; i ++) {
                                    HashMap<String, Object> item = new HashMap<>();
                                    item.put("value", values[i]);
                                    msgData.put(keys[i], item);
                                }


                                wechatapi.sendMsg(user.getOpenid(), msgData, url);
                            }catch (Exception e) {
                                System.out.println(row);
                                e.printStackTrace();
                            }
                        }
                    }

//                    if(pageNo > 0) {
//                        continue;
//                    }




                    List<HashMap> taskList = openapi.lastunTaskList(user.getAccount());
                    if(taskList != null && !taskList.isEmpty()) {

                        long time = Instant.now().getEpochSecond();

                        for(HashMap row:taskList) {
                            try{
                                HashMap<String, HashMap<String, Object>> msgData = new HashMap<>();
                                String title = (String) row.get("subject");
                                if(title.length() > 20) {
                                    title = title.substring(0, 17) + "...";
                                }
                                String mobileUrl = (String) row.get("h5ViewUrl");
                                String pcUrl = (String) row.get("pcViewUrl");

                                String url = baseUrl + ("?mobileUrl=" + URLEncoder.encode(mobileUrl, StandardCharsets.UTF_8)) + "&pcUrl=" + URLEncoder.encode(pcUrl, StandardCharsets.UTF_8);

                                String createTime = (String) row.get("createTime");

                                String[] parts = createTime.split("\\.");
                                createTime = parts[0];




                                LocalDateTime dateTime = LocalDateTime.parse(createTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
                                Instant instant = dateTime.atZone(ZoneId.systemDefault()).toInstant();
                                long timestamp = instant.getEpochSecond();


                                if((time - timestamp) > 120) continue;

                                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                                String formattedDateTime = dateTime.format(formatter);



                                String[] values = {title, formattedDateTime};
                                for(int i = 0; i < keys.length; i ++) {
                                    HashMap<String, Object> item = new HashMap<>();
                                    item.put("value", values[i]);
                                    msgData.put(keys[i], item);
                                }

                                wechatapi.sendMsg(user.getOpenid(), msgData, url);
                            }catch (Exception e) {
                                System.out.println(row);
                                e.printStackTrace();
                            }
                        }

                    }

                }
            }


            if(users.size() < pageSize) {
                break;
            }

        }



    }
}
